package com.gewu.pm.ui.activity.sales;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.gewu.pm.R;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.http.glide.GlideApp;
import com.gewu.pm.other.IntentKey;
import com.gewu.pm.ui.activity.ImageSelectActivity;
import com.gewu.pm.ui.dialog.AddressDialog;
import com.gewu.pm.ui.dialog.SelectSalesRegionDialog;
import com.gewu.pm.utils.TextStarUtils;
import com.gewu.pm.utils.eventbus.EventBean;
import com.gewu.pm.utils.eventbus.EventBusUtil;
import com.gewu.pm.utils.eventbus.EventCode;
import com.hjq.base.BaseDialog;

import java.io.File;
import java.util.List;

/**
 * 新增销售线索确认页面（第二页 - 确认页）
 */
public final class SalesLeadAddTwoActivity extends AppActivity
        implements ImageSelectActivity.OnPhotoSelectListener {

    // 基本信息
    private TextView mLeadNameLabel;
    private EditText mLeadNameEdit;
    private TextView mLeadCodeLabel;
    private EditText mLeadCodeEdit;
    private TextView mSalesAreaLabel;
    private TextView mSalesAreaValue;
    private TextView mCreatorLabel;
    private TextView mCreatorValue;
    private TextView mLeadTypeLabel;
    private TextView mLeadTypeValue;
    private TextView mFacadePhotoLabel;
    private ImageView mFacadePhotoView;
    private ImageView mFacadePhotoDeleteView;
    private String mFacadePhotoPath;
    private TextView mStorePhotoLabel;
    private ImageView mStorePhotoView;
    private ImageView mStorePhotoDeleteView;
    private String mStorePhotoPath;

    // 地区
    private TextView mLocationAreaLabel;
    private TextView mLocationAreaValue;
    private TextView mDetailedAddressLabel;
    private EditText mDetailedAddressEdit;
    private TextView mLatLngLabel;
    private TextView mLatLngValue;

    // 提交按钮
    private TextView mSubmitButton;

    // 当前选择的图片类型
    private int mCurrentPhotoType = 0;  // 0-门头照，1-店内照片

    public static void start(Context context, String leadName, String leadCode, 
                            String locationArea, String detailedAddress, String facadePhotoPath) {
        Intent intent = new Intent(context, SalesLeadAddTwoActivity.class);
        intent.putExtra(IntentKey.TITLE, leadName);
        intent.putExtra(IntentKey.ID, leadCode);
        intent.putExtra(IntentKey.ADDRESS, locationArea);
        intent.putExtra(IntentKey.CONTENT, detailedAddress);
        intent.putExtra(IntentKey.IMAGE, facadePhotoPath);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.sales_lead_confirm_activity;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        // 基本信息
        mLeadNameLabel = findViewById(R.id.tv_lead_name_label);
        mLeadNameEdit = findViewById(R.id.et_lead_name);
        mLeadCodeLabel = findViewById(R.id.tv_lead_code_label);
        mLeadCodeEdit = findViewById(R.id.et_lead_code);
        mSalesAreaLabel = findViewById(R.id.tv_sales_area_label);
        mSalesAreaValue = findViewById(R.id.tv_sales_area_value);
        mCreatorLabel = findViewById(R.id.tv_creator_label);
        mCreatorValue = findViewById(R.id.tv_creator_value);
        mLeadTypeLabel = findViewById(R.id.tv_lead_type_label);
        mLeadTypeValue = findViewById(R.id.tv_lead_type_value);
        mFacadePhotoLabel = findViewById(R.id.tv_facade_photo_label);
        mFacadePhotoView = findViewById(R.id.iv_facade_photo);
        mFacadePhotoDeleteView = findViewById(R.id.iv_facade_photo_delete);
        mStorePhotoLabel = findViewById(R.id.tv_store_photo_label);
        mStorePhotoView = findViewById(R.id.iv_store_photo);
        mStorePhotoDeleteView = findViewById(R.id.iv_store_photo_delete);

        // 地区
        mLocationAreaLabel = findViewById(R.id.tv_location_area_label2);
        mLocationAreaValue = findViewById(R.id.tv_location_area_value2);
        mDetailedAddressLabel = findViewById(R.id.tv_detailed_address_label2);
        mDetailedAddressEdit = findViewById(R.id.et_detailed_address2);
        mLatLngLabel = findViewById(R.id.tv_lat_lng_label2);
        mLatLngValue = findViewById(R.id.tv_lat_lng_value2);

        // 提交按钮（使用内部按钮 ID）
        mSubmitButton = findViewById(R.id.tv_bottom_button);

        // 设置必填标记
        TextStarUtils.setRequiredText(mLeadNameLabel, getString(R.string.lead_name));
        TextStarUtils.setRequiredText(mLeadCodeLabel, getString(R.string.lead_code));
        TextStarUtils.setRequiredText(mSalesAreaLabel, getString(R.string.sales_area));
        TextStarUtils.setRequiredText(mCreatorLabel, getString(R.string.creator));
        TextStarUtils.setRequiredText(mFacadePhotoLabel, getString(R.string.facade_photo));
        TextStarUtils.setRequiredText(mStorePhotoLabel, getString(R.string.store_photo));
        TextStarUtils.setRequiredText(mLocationAreaLabel, getString(R.string.location_area));
        TextStarUtils.setRequiredText(mDetailedAddressLabel, getString(R.string.detailed_address));
        TextStarUtils.setRequiredText(mLatLngLabel, getString(R.string.latitude_longitude));

        // 设置图片点击事件
        mFacadePhotoView.setOnClickListener(v -> {
            mCurrentPhotoType = 0;  // 门头照
            ImageSelectActivity.start(this, 1, this);
        });
        mStorePhotoView.setOnClickListener(v -> {
            mCurrentPhotoType = 1;  // 店内照片
            ImageSelectActivity.start(this, 1, this);
        });

        // 设置图片删除按钮点击事件
        mFacadePhotoDeleteView.setOnClickListener(v -> deleteFacadePhoto());
        mStorePhotoDeleteView.setOnClickListener(v -> deleteStorePhoto());

        // 设置点击事件
        setOnClickListener(mSalesAreaValue, mLocationAreaValue, mLatLngValue, mLeadTypeValue, mSubmitButton);
    }

    @Override
    protected void initData() {
        // 接收第一页传递的数据
        String leadName = getString(IntentKey.TITLE);
        String locationArea = getString(IntentKey.ADDRESS);
        String detailedAddress = getString(IntentKey.CONTENT);
        mFacadePhotoPath = getString(IntentKey.IMAGE);

        // 填充数据
        if (!TextUtils.isEmpty(leadName)) {
            mLeadNameEdit.setText(leadName);
        }
        if (!TextUtils.isEmpty(locationArea)) {
            mLocationAreaValue.setText(locationArea);
        }
        if (!TextUtils.isEmpty(detailedAddress)) {
            mDetailedAddressEdit.setText(detailedAddress);
        }
        if (!TextUtils.isEmpty(mFacadePhotoPath)) {
            updateFacadePhoto();
        }
    }

    private String mProvince = "浙江省";//省
    private String mCity = "杭州市";//市
    private String mArea = "滨江区";//区
    @SingleClick
    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view == mSalesAreaValue) {// 选择销售区域
            new SelectSalesRegionDialog.Builder(this)
                    .setDefaultRegion(mSalesAreaValue.getText().toString())
                    .setListener(new SelectSalesRegionDialog.OnListener() {
                        @Override
                        public void onSelected(BaseDialog dialog, String region) {
                            // 显示选中的区域
                            mSalesAreaValue.setText(region);
                            mSalesAreaValue.setTextColor(getResources().getColor(R.color.cb3));
                        }
                    })
                    .show();
            // TODO: 打开销售区域选择
        } else if (view == mLocationAreaValue) {
            // 选择所在地区
            new AddressDialog.Builder(this)
                    //.setTitle("选择地区")
                    // 设置默认省份
                    .setProvince(mProvince)
                    // 设置默认城市（必须要先设置默认省份）
                    .setCity(mCity)
                    // 不选择县级区域
                    //.setIgnoreArea()
                    .setListener((dialog, province, city, area) -> {
                        String address = province + city + area;
                        if (!mLocationAreaValue.getText().equals(address)) {
                            mProvince = province;
                            mCity = city;
                            mArea = area;
                            mLocationAreaValue.setText(address);
                        }
                    })
                    .show();
        } else if (view == mLatLngValue) {
            // 获取经纬度
            toast("点击获取经纬度");
            // TODO: 获取经纬度
        } else if (view == mLeadTypeValue) {
            // 选择线索类型
            toast("选择线索类型");
            // TODO: 打开线索类型选择
        } else if (view == mSubmitButton) {
            // 验证必填项
            String leadName = mLeadNameEdit.getText().toString().trim();
//            if (TextUtils.isEmpty(leadName)) {
//                toast("请输入线索名称");
//                return;
//            }

            String leadCode = mLeadCodeEdit.getText().toString().trim();
//            if (TextUtils.isEmpty(leadCode)) {
//                toast("请输入线索编码");
//                return;
//            }
//
//            if (TextUtils.isEmpty(mFacadePhotoPath)) {
//                toast("请上传门头照");
//                return;
//            }
//            if (TextUtils.isEmpty(mStorePhotoPath)) {
//                toast("请上传店内照片");
//                return;
//            }

            // 提交成功
            toast("提交成功");

            // 发送 EventBus 事件通知第一页关闭
            EventBusUtil.sendEvent(new EventBean<>(EventCode.SALES_LEAD_ADDED));

            // 关闭当前页面（第一页会通过 EventBus 自动关闭）
            finish();
        }
    }

    /**
     * {@link ImageSelectActivity.OnPhotoSelectListener}
     * 图片选择回调
     */
    @Override
    public void onSelected(List<String> images) {
        if (images != null && !images.isEmpty()) {
            String selectedImage = images.get(0);
            
            if (mCurrentPhotoType == 0) {
                // 门头照
                mFacadePhotoPath = selectedImage;
                updateFacadePhoto();
            } else if (mCurrentPhotoType == 1) {
                // 店内照片
                mStorePhotoPath = selectedImage;
                updateStorePhoto();
            }
        }
    }

    @Override
    public void onCancel() {
        // 取消选择
    }

    /**
     * 更新门头照显示
     */
    private void updateFacadePhoto() {
        if (!TextUtils.isEmpty(mFacadePhotoPath) && new File(mFacadePhotoPath).exists()) {
            GlideApp.with(this)
                    .load(new File(mFacadePhotoPath))
                    .placeholder(R.drawable.add_ic)
                    .error(R.drawable.add_ic)
                    .into(mFacadePhotoView);
            mFacadePhotoView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            mFacadePhotoDeleteView.setVisibility(View.VISIBLE);
        } else {
            mFacadePhotoView.setImageResource(R.drawable.add_ic);
            mFacadePhotoView.setScaleType(ImageView.ScaleType.CENTER);
            mFacadePhotoDeleteView.setVisibility(View.GONE);
        }
    }

    /**
     * 更新店内照片显示
     */
    private void updateStorePhoto() {
        if (!TextUtils.isEmpty(mStorePhotoPath) && new File(mStorePhotoPath).exists()) {
            GlideApp.with(this)
                    .load(new File(mStorePhotoPath))
                    .placeholder(R.drawable.add_ic)
                    .error(R.drawable.add_ic)
                    .into(mStorePhotoView);
            mStorePhotoView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            mStorePhotoDeleteView.setVisibility(View.VISIBLE);
        } else {
            mStorePhotoView.setImageResource(R.drawable.add_ic);
            mStorePhotoView.setScaleType(ImageView.ScaleType.CENTER);
            mStorePhotoDeleteView.setVisibility(View.GONE);
        }
    }

    /**
     * 删除门头照
     */
    @SingleClick
    private void deleteFacadePhoto() {
        mFacadePhotoPath = null;
        updateFacadePhoto();
        toast("已删除门头照");
    }

    /**
     * 删除店内照片
     */
    @SingleClick
    private void deleteStorePhoto() {
        mStorePhotoPath = null;
        updateStorePhoto();
        toast("已删除店内照片");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放资源
    }
}
